import time
import mraa

usleep = lambda x: time.sleep(x / 1000000.0)

dio = mraa.Gpio(32)


def get_distance():
    dio.dir(mraa.DIR_OUT)
    dio.write(0)
    usleep(2)
    dio.write(1)
    usleep(20)
    dio.write(0)

    dio.dir(mraa.DIR_IN)

    t0 = time.time()
    count = 0
    while count < 1000:
        if dio.read():
            break
        count += 1
    
    t1 = time.time()

    count = 0
    while count < 10000:
        if not dio.read():
            break
        count += 1
    
    t2 = time.time()

    # [int((t2 - t1) * 1000000), int((t1 - t0) * 1000000)]
    distance = int((t2 - t1) * 1000000 / 29 / 2)

    return distance


for i in range(100):
    print(get_distance())
    time.sleep(1)
